<template>
  <page-header-wrapper>
    <a-card class="table-card">
      <JeepaySearchForm :searchConditionNum="6" :searchFunc="searchFunc" :resetFunc="onReset">
        <jeepay-text-up v-model:value="vdata.searchData.storeId" :placeholder="'门店ID'" />
        <jeepay-text-up v-model:value="vdata.searchData.deviceNo" :placeholder="'激活码'" />
        <jeepay-text-up v-model:value="vdata.searchData.deviceName" :placeholder="'激活码名称'" />
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData.provider" placeholder="所属厂商">
            <a-select-option value="">全部</a-select-option>
            <a-select-option v-for="item in pluginList" :key="item.value" :value="item.value">{{ item.text }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData.state" placeholder="激活状态">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="0">待激活</a-select-option>
            <a-select-option value="1">已激活</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData.bindState" placeholder="绑定状态">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="0">未绑定</a-select-option>
            <a-select-option value="1">已绑定</a-select-option>
          </a-select>
        </a-form-item>
      </JeepaySearchForm>
      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :init-data="true"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="vdata.searchData"
        row-key="deviceId"
        @btnLoadClose="btnLoading=false"
      >
        <template #topBtnSlot>
          <a-button type="primary" @click="addFunc"><plus-outlined />申请新激活码</a-button>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'provider'">
            <a-tag :key="record.provider" color="processing">
              {{ (pluginList.find(item => item.value == record.provider) as any).text || '其他' }}
            </a-tag>
          </template>
          
          <template v-if="column.key === 'state'">
            <a-tag v-if="record.state == 0" color="orange">待激活</a-tag>
            <a-switch v-else :checked="record.state == 1 ? true : false" @change="(state) => { return updateState(record.deviceId, state)}" />
          </template>

          <template v-if="column.key === 'expiredTime'">
            {{ JSON.parse(record.deviceParams).expiredTime == 0 ? '长期有效' : dateUtil.formatDate(JSON.parse(record.deviceParams).expiredTime) }}
          </template>

          <template v-if="column.key === 'activeTime'">
            <template v-if="record.deviceParams && JSON.parse(record.deviceParams).activeTime">
              {{ JSON.parse(record.deviceParams).activeTime }}
            </template>
          </template>
 
          <template v-if="column.key === 'operation'">
            <!-- 操作列插槽 -->
            <JeepayTableColumns>
              <a-button v-if="$access('ENT_DEVICE_PLUGIN_CDKEY_EDIT')" type="link" @click="editFunc(record)">修改</a-button>
              <!-- <a-button v-if="$access('ENT_DEVICE_PLUGIN_CDKEY_EDIT') && record.bindState == 1" type="link" @click="deBindFunc(record.deviceId)">解绑</a-button> -->
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>

    <!-- 新增页面组件  -->
    <InfoAddOrEdit ref="infoAddOrEdit" :callbackFunc="searchFunc" />
  </page-header-wrapper>
</template>
<script setup lang="ts">
import {$unbindDevice, API_URL_STORE_DEVICE, req, reqLoad} from '@/api/manage'
import InfoAddOrEdit from '../CommonAddOrEdit.vue'
import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
import dateUtil from '@/utils/dateUtil.js'
import provider from '../provider.json'

const pluginList = provider.plugin

const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties

const infoAddOrEdit = ref()
const infoTable = ref()
const deviceType = 5

let tableColumns = reactive([
  { title: '激活码', fixed: 'left', dataIndex: 'deviceNo', },
  { key: 'provider', title: '厂商', dataIndex: 'provider',},
  { title: '激活码名称', dataIndex: 'deviceName', },
  { title: '门店编号', dataIndex: 'storeId',},
  { key: 'appId', dataIndex: 'appId', title: '应用ID', },
  { key: 'state', title: '激活状态',},
  { key: 'activeTime', title: '激活时间',},
  { key: 'expiredTime', title: '有效期止',},
  { dataIndex: 'createdAt', title: '创建日期',},
  { key: 'operation', title: '操作', fixed: 'right', align: 'center', }
])

  let btnLoading = ref(false)
  const vdata = reactive({
    searchData: {} as any
  }) as any

  function reqTableDataFunc(params: any) { // 请求table接口数据
    return req.list(API_URL_STORE_DEVICE, Object.assign({ deviceType: deviceType }, params))
  }
  function searchFunc () { // 点击【查询】按钮点击事件
    btnLoading.value = true
    infoTable.value.refTable(true)
  }
  function addFunc () { // 业务通用【新增】 函数
    $infoBox.message.success('请联系运营平台申请')
  }
  function editFunc (record: any) { // 业务通用【修改】 函数
    infoAddOrEdit.value.show(record)
  }
  function onReset(){ //重置搜索内容
    vdata.searchData = {}
  }
  function updateState (recordId, state) { // 【更新状态】
      return new Promise<void>((resolve, reject) => {
        $infoBox.confirmDanger('确认解除激活？', '解除激活后，该激活码将不可用！', () => {
          return reqLoad.updateById(API_URL_STORE_DEVICE, recordId, { state: state }).then(res => {
            searchFunc()
            resolve()
          }).catch(err => reject(err))
        },
          () => {
          reject(new Error())
        })
      })
    }

  // 解绑激活码
  function deBindFunc(recordId) {
    const title = '确认解绑？'
    const content = '解绑后商户将无法使用该激活码！'
    $infoBox.confirmDanger(title, content, () => {
      return $unbindDevice(recordId).then(res => {
        infoTable.value.refTable(true)
        $infoBox.message.success('解绑成功')
      })
    })
  }
</script>
